import React from 'react'
import request from '@/helpers/service'

export const exportFnc = (url, linkParam = {}, method = 'get') => {
  if (method === 'post') {
    request({
      url,
      method: 'post',
      responseType: 'arraybuffer',
      headers: {
        'Content-Type': 'application/vnd.ms-excel'
      },
      data: linkParam
    }).then((res) => {
      const disposition = res.headers['content-disposition']
      const fileName = disposition.slice(disposition.indexOf('""') + 1, -1)
      const blob = new Blob([res.data])
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = decodeURI(escape(fileName))
      link.click()
      link.remove()
    })
    return
  }
  request({
    url,
    responseType: 'arraybuffer',
    headers: {
      'Content-Type': 'application/vnd.ms-excel'
    },
    data: linkParam
  }).then((res) => {
    const disposition = res.headers['content-disposition']
    const fileName = disposition.slice(disposition.indexOf('""') + 1, -1)
    const blob = new Blob([res.data])
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = decodeURI(escape(fileName).replace(/[ （]/g, '(').replace(/[（]/g, ')'))
    link.click()
    link.remove()
  })
}

class ExportExcel extends React.Component {
  exportClick = () => {
    const { linkParam = {}, url, method = 'get' } = this.props
    if (method === 'post') {
      request({
        url,
        responseType: 'arraybuffer',
        headers: {
          'Content-Type': 'application/vnd.ms-excel'
        },
        data: linkParam
      }).then((res) => {
        const disposition = res.headers['content-disposition']
        const fileName = disposition.slice(disposition.indexOf('""') + 1, -1)
        const blob = new Blob([res.data])
        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.download = decodeURI(escape(fileName))
        link.click()
        link.remove()
      })
      return
    }
    request({
      url,
      responseType: 'arraybuffer',
      headers: {
        'Content-Type': 'application/vnd.ms-excel'
      },
      data: linkParam
    }).then((res) => {
      const disposition = res.headers['content-disposition']
      const fileName = disposition.slice(disposition.indexOf('""') + 1, -1)
      const blob = new Blob([res.data])
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = decodeURI(escape(fileName))
      link.click()
      link.remove()
    })
  }

  render() {
    const { children } = this.props
    return (
      <div className="exportExcel" onClick={this.exportClick} style={{ cursor: 'pointer' }}>
        {children}
      </div>
    )
  }
}

export default ExportExcel
